package com.zt.teacher.shiro;

import com.zt.common.pojo.Teachers;
import com.zt.teacher.service.TeacherService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * description:
 * author:zt
 * date:2021-12-07
 */
public class PwdRealm extends AuthorizingRealm {

    @Autowired
    private TeacherService teacherService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String teacherId = (String) token.getPrincipal();
        Teachers teacher = teacherService.findTeacherById(teacherId);

        if (teacher == null){
            throw new UnknownAccountException();
        }

        //密码加盐处理
        return new SimpleAuthenticationInfo(teacher,teacher.getPassword(), ByteSource.Util.bytes(teacher.getSalt()),getName());
    }
}
